package com.jerry.server;

public class Acceptor<T> implements Runnable {

    private AbstractEndpoint<T> endpoint;

    private String threadName;

    public String getThreadName() {
        return threadName;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public Acceptor(AbstractEndpoint<T> endpoint) {
        this.endpoint = endpoint;
    }


    public void run() {
        while (endpoint.isRunning()) {//如果是运行中，则进行循环抓取
            while (endpoint.isRunning() && endpoint.isPaused()) {//如果是停止，则阻塞当前线程，知道停止开启

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // Ignore
                }
            }
            if (!endpoint.isRunning()) {//如果是端点不运行，则直接退出
                break;
            }
            T socket = null;
            try {
              socket =   endpoint.serverSocketAccept();
            } catch (Exception e) {


            }
            // 如果端点还在启用，并且没暂停，则对socket的连接进行响应
            if (endpoint.isRunning() && !endpoint.isPaused()) {

                if (!endpoint.setSocketOptions(socket)) {//如果在建立连接的相关处理时报错，则关闭socket
                    endpoint.closeSocket(socket);
                }
            } else {
                //如果端点已经停止或者已经暂停，则销毁收到的socket
                endpoint.destroySocket(socket);
            }
        }
    }
}